<?
include("constants.php");

//-----------clasa MySQLDB este folosita pentru operatiile asupra bd---------

class MySQLDB
{
	//conexiunea mysql
	var $connection;
	//membrii on-line
	var $num_active_users;
	//vizitatori on-line
	var $num_active_guests;
	//numar total de membrii
	var $num_members;

	// constructorul clasei
	function __construct()
	{
		$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
		mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());

		//valoare implicita, valoarea reala poate fi aflata accesand functia getNumMembers()
		$this->num_members=-1;
		$this->getNumMembers();

		//daca in constants valoarea lui TRACK_VISITORS este true se calculeaza valorile
		if (TRACK_VISITORS)
		{
			$this->calcNumActiveUsers();
			$this->calcNumActiveGuests();
		}

		//echo("end db construct");
	}

	//verifica existenta username-ului in bd, si daca acesta exista verifica parola
	//daca username-ul nu este gasit returneaza 1
	//daca parolele nu se potrivesc returneaza 2
	//succes, returneaza 0
	function confirmUserPass($username, $password)
	{
		//pt interogarea sql-> adauga slash
		if (!get_magic_quotes_gpc())
		{
			$username=addslashes($username);
		}

		//verificare existenta username in bd
		$q     ="SELECT password FROM " . TBL_USERS . " WHERE username = '$username'";
		$result=mysql_query($q, $this->connection);

		if (!$result || (mysql_numrows($result) < 1))
		{
			return 1;
		}

		//returnare parola pentru username gasit
		$dbarray            =mysql_fetch_array($result);
		$dbarray['password']=stripslashes($dbarray['password']);
		$password           =stripslashes($password);

		//verifica daca parolele coincid
		if ($password == $dbarray['password'])
		{
			return 0;
		}
		else
		{
			return 2;
		}
	}

	//verifica daca un anumit user este in bd si verifica daca userId-urile se potrivesc
	//user nu est in bd, returneaza 1
	//userId nu sunt aceleasi, returneaza 2
	//succes, returneaza 0
	function confirmUserID($username, $userid)
	{
		/* Add slashes if necessary (for query) */
		if (!get_magic_quotes_gpc())
		{
			$username=addslashes($username);
		}

		//verifica daca username-ul este in bd
		$q     ="SELECT userid FROM " . TBL_USERS . " WHERE username = '$username'";
		$result=mysql_query($q, $this->connection);

		if (!$result || (mysql_numrows($result) < 1))
		{
			return 1;
		}

		//returneaza userId din bd pentru user
		$dbarray          =mysql_fetch_array($result);
		$dbarray['userid']=stripslashes($dbarray['userid']);
		$userid           =stripslashes($userid);

		//verifica daca userId sunt aceleasi
		if ($userid == $dbarray['userid'])
		{
			return 0;
		}
		else
		{
			return 2;
		}
	}

	//verifica la inregistrare daca username-ul dorit de noul utilizator poate fi folosit
	//returneaza 0 daca username-ul poate fi folosit
	function usernameTaken($username)
	{
		if (!get_magic_quotes_gpc())
		{
			$username=addslashes($username);
		}

		$q     ="SELECT username FROM " . TBL_USERS . " WHERE username = '$username'";
		$result=mysql_query($q, $this->connection);
		return (mysql_numrows($result) > 0);
	}

	//verifica daca unui anumit username i-a fost restrictionat accesul de admin
	//returneaza true daca username-ul a fost restrictionat
	function usernameBanned($username)
	{
		if (!get_magic_quotes_gpc())
		{
			$username=addslashes($username);
		}

		$q     ="SELECT username FROM " . TBL_BANNED_USERS . " WHERE username = '$username'";
		$result=mysql_query($q, $this->connection);
		return (mysql_numrows($result) > 0);
	}

	//adaugare membru nou in bd
	//returneaza true pentru succes
	function addNewUser($username, $password, $email){
		$time=time();

		//atribuire nivel de acces
		if (strcasecmp($username, ADMIN_NAME) == 0){
			$ulevel=ADMIN_LEVEL;
		}else{
			$ulevel=USER_LEVEL;
		}

		$q="INSERT INTO " . TBL_USERS . " VALUES ('$username', '$password', '0', $ulevel, '$email', $time)";
		return mysql_query($q, $this->connection);
	}

	//modifica anumite caracteristici pentru un username
	//tip de return: resource
	/**
	 * modificare field user
	 *
	 * @param string $username
	 * @param string $field
	 * @param string $value
	 * @return resource
	 */
	function updateUserField($username, $field, $value)
	{
		$q="UPDATE " . TBL_USERS . " SET " . $field . " = '$value' WHERE username = '$username'";
		return mysql_query($q, $this->connection);
	}

	//informatii despre un utilizator
	//pentru succes, returneaza un array
	//pentru esec, returneaza NULL
	function getUserInfo($username)
	{
		$q     ="SELECT * FROM " . TBL_USERS . " WHERE username = '$username'";
		$result=mysql_query($q, $this->connection);

		if (!$result || (mysql_numrows($result) < 1))
		{
			return NULL;
		}

		$dbarray=mysql_fetch_array($result);
		return $dbarray;
	}

	//calculeaza numarul de membrii inregistrati
	//membrii cu restrictii de acces nu sunt inclusi
	function getNumMembers()
	{
		if ($this->num_members < 0)
		{
			$q                ="SELECT * FROM " . TBL_USERS;
			$result           =mysql_query($q, $this->connection);
			$this->num_members=mysql_num_rows($result);
		}
		//    return $this->num_members;
	}

	//calculeaza numarul de membrii on-line
	function calcNumActiveUsers()
	{
		$q                     ="SELECT * FROM " . TBL_ACTIVE_USERS;
		$result                =mysql_query($q, $this->connection);
		$this->num_active_users=mysql_num_rows($result);
	}

	//calculeaza numarul de vizitatori neinregistrati on-line
	function calcNumActiveGuests()
	{
		$q                      ="SELECT * FROM " . TBL_ACTIVE_GUESTS;
		$result                 =mysql_query($q, $this->connection);
		$this->num_active_guests=mysql_num_rows($result);
	}

	//update pentru timestamp-ul fiecarui user
	//folosit pentru elininare userilor care sunt inactivi o anumita perioada
	//adauga user-ul in tabela de useri activi sau modifica timestamp-ul daca deja se afla
	//in tabela
	function addActiveUser($username, $time)
	{
		$q="UPDATE " . TBL_USERS . " SET timestamp = '$time' WHERE username = '$username'";
		mysql_query($q, $this->connection);

		if (!TRACK_VISITORS)
		return;

		$q="REPLACE INTO " . TBL_ACTIVE_USERS . " VALUES ('$username', '$time')";
		mysql_query($q, $this->connection);
		$this->calcNumActiveUsers();
	}

	///adauga un nou vizitator in tabela de vizitatori on-line
	function addActiveGuest($ip, $time)
	{
		if (!TRACK_VISITORS)
		return;

		$q="REPLACE INTO " . TBL_ACTIVE_GUESTS . " VALUES ('$ip', '$time')";
		mysql_query($q, $this->connection);
		$this->calcNumActiveGuests();
	}

	//sterge din tabele membrilor on-line un anumit user
	function removeActiveUser($username)
	{
		if (!TRACK_VISITORS)
		return;

		$q="DELETE FROM " . TBL_ACTIVE_USERS . " WHERE username = '$username'";
		mysql_query($q, $this->connection);
		$this->calcNumActiveUsers();
	}

	//sterge din tabele vizitatorilor on-line un anumit ip
	function removeActiveGuest($ip)
	{
		if (!TRACK_VISITORS)
		return;

		$q="DELETE FROM " . TBL_ACTIVE_GUESTS . " WHERE ip = '$ip'";
		mysql_query($q, $this->connection);
		$this->calcNumActiveGuests();
	}

	//sterge membrii cu o perioada de inactivitate mai mare decat cea stabilita de admin
	function removeInactiveUsers()
	{
		if (!TRACK_VISITORS)
		return;

		$timeout=time() - USER_TIMEOUT * 60;
		$q      ="DELETE FROM " . TBL_ACTIVE_USERS . " WHERE timestamp < $timeout";
		mysql_query($q, $this->connection);
		$this->calcNumActiveUsers();
	}

	//sterge vizitatorii cu o perioada de inactivitate mai mare decat cea stabilita de admin
	function removeInactiveGuests()
	{
		if (!TRACK_VISITORS)
		return;

		$timeout=time() - GUEST_TIMEOUT * 60;
		$q      ="DELETE FROM " . TBL_ACTIVE_GUESTS . " WHERE timestamp < $timeout";
		mysql_query($q, $this->connection);
		$this->calcNumActiveGuests();
	}

	/**
	 * creare proj nou-> inreg in bd
	 * @param String $projId, String $name, String $idOwner
	 * @return true
	 */
	public function recordNewProject($name, $idOwner){
		$projId=rand(5,50000);
		try {
			$q="INSERT INTO ".TBL_PROJECTS." VALUES ('$projId', '$name', '$idOwner')";
			$this->query($q);
			return true;
		}catch (Exception $e){
			echo $e->getMessage();
		}
	}

	/**
	 * returneaza array cu proiectele unui user
	 *
	 * @param String $userId
	 * @return Array or false if errors
	 */
	public function getUserProjects($userName){
		try {
			/*			$q="SELECT numeproiect FROM ".TBL_PROJECTS." WHERE owner='".$userName."'";
			 $result=$this->query($q);
			 $prj=array();
			 while ($line=mysql_fetch_array($result, MYSQL_ASSOC)){
				foreach ($line as $ln){
				$prj[]=$ln;
				}
				}*/
			$dom=new DOMDocument();
			$dom->load("xmlDb/userProjects.xml");
			$xsl=new DOMDocument();
			$xsl->load("include/xsl/openProjListFriends.xsl");
			$proc=new XSLTProcessor();
			$proc->importStylesheet($xsl);
			$proc->setParameter("", "username", $_SESSION['username']);
			$prj=explode(";",rtrim($proc->transformToXml($dom)));
			array_pop($prj);
			return $prj;
		}catch (Exception $e){
			return false;
		}
	}

	//efectueaza o anumita interogare pe baza de date
	//tip return: resource
	function query($query) {
		return mysql_query($query, $this->connection);
	}
}

;

//creaza instanta a clasei
//$database=new MySQLDB;
?>